<script setup lang="ts">
import { onMounted, ref } from '@vue/runtime-dom'
import {
  Scene,
  PerspectiveCamera,
  WebGLRenderer,
  BoxGeometry,
  MeshBasicMaterial,
  Mesh,
} from 'three'

const threeRef = ref<HTMLDivElement>()
const scene = new Scene()
const renderer = new WebGLRenderer()
const camera = ref()

const getWrapWidthAndHeight = () => {
  return {
    width: threeRef.value?.clientWidth || 0,
    height: threeRef.value?.clientHeight || 0,
  }
}

const createBox = () => {
  const geometry = new BoxGeometry(1, 1, 1)
  const material = new MeshBasicMaterial({ color: 0x00ff00 })
  const cube = new Mesh(geometry, material)
  return cube
}

const initThreeBase = (width: number, height: number) => {
  camera.value = new PerspectiveCamera(75, width / height, 0.1, 1000)
  renderer.setSize(width, height)
  camera.value.position.z = 5
}

const animate = () => {
  requestAnimationFrame(animate)
  moveBox()
  renderer.render(scene, camera.value)
}

const box = createBox()
const moveBox = () => {
  box.rotation.z += 0.01
}

const init = () => {
  const wrapInfo = getWrapWidthAndHeight()

  initThreeBase(wrapInfo.width, wrapInfo.height)
  threeRef.value?.appendChild(renderer.domElement)

  scene.add(box) // 默认添加到 (0,0,0)

  animate()
}

onMounted(() => {
  init()
})
</script>

<template>
  <div class="content" ref="threeRef"></div>
</template>

<style scoped>
.content {
  width: 500px;
  height: 500px;
  border: 1px solid red;
}
</style>
